//
//  OcrView.m  参考IDCard/IDCartViewController.m
//  ocr_plugin
//
//  Created by apple on 2021/9/15.
//

#import "OcrView.h"

#import "OcrPCaptureManager.h"

#import "NSString+OcrPExtend.h"

///扩展
@interface OcrView ()<OcrPCaptureManagerDelegate>
@property (nonatomic, strong) OcrPCaptureManager *captureManager;

@property (copy, nonatomic) NSString* imgPath;
@property (copy, nonatomic) NSString* headPath;

@property (copy, nonatomic) OcrViewSuccessBlock successBlock;
@property (copy, nonatomic) OcrViewFailurelock failurelock;

@end


///实现
@implementation OcrView

- (void)dealloc{
    NSLog(@"OcrView dealloc");
}
 
///实现定义方法
- (void)achieveResult:(OcrViewSuccessBlock)block{
    self.successBlock = block;
}
- (void)achieveError:(OcrViewFailurelock)block{
    self.failurelock = block;
}
- (void)pause{
    [self.captureManager stopSession];
}
- (void)resume{
    [self.captureManager runSession];
}
- (void)close{
    [self.captureManager stopSession];
}

- (void)takePhotoCamera{
    self.captureManager.cropEnable = NO;
    [self.captureManager takePhotoCamera];
}


- (void)takePhotoCameraWithRect{
    self.captureManager.cropEnable = YES;
    [self.captureManager takePhotoCamera];
}

- (void)takePhotoLibrary{
    [self.captureManager takePhotoLibrary];
}

- (void)switchCamera{
    [self.captureManager switchCamera];
}

- (void)setOcrFilePath:(NSString *)imgPath headPath:(NSString *)headPath{
    self.imgPath = imgPath;
    self.headPath = headPath;
}

- (void)configAreaFrame:(CGRect)areaFrame faceFrame:(CGRect)faceFrame{
    [self.captureManager configAreaFrame:areaFrame faceFrame:faceFrame];
}

/// 初始化
- (instancetype)initWithFrame:(CGRect)frame args:(NSDictionary *)args captureSessionQueue:(dispatch_queue_t)captureSessionQueue{
    double width = frame.size.width;
    double height = frame.size.height;
    if (args!=nil&&[args isKindOfClass:[NSDictionary class]]) {
        if ([args.allKeys containsObject:@"areaWidth"]) {
            width = [args[@"areaWidth"] doubleValue];
        }
        if ([args.allKeys containsObject:@"areaHeight"]) {
            height = [args[@"areaHeight"] doubleValue];
        }
    }
    
    NSLog(@"OcrView width %f ,height %f",width, height);
    if (width==0||height==0) {
        frame = [UIScreen mainScreen].bounds;
    } else {
        frame = CGRectMake(0, 0, width, height);
    }
    
    if(self = [super initWithFrame:frame]){
        self.captureManager = [[OcrPCaptureManager alloc] initWithCaptureSessionQueue:captureSessionQueue];
        [self initData:args];
    }
    return self;
}

- (void)initData:(NSDictionary *)args{
    // 界面设置为黑色，解决跳转后先白后黑
    self.backgroundColor = UIColor.blackColor;
    
    BOOL scanEnable = true;
    NSInteger type = 0;
    
    BOOL takePhotoRotated = true;
    BOOL autoStopScan = true;
    
    BOOL fullArea = NO;
    
    if (args!=nil&&[args isKindOfClass:[NSDictionary class]]) {
        
        if ([args.allKeys containsObject:@"scanEnable"]) {
            scanEnable = [args[@"scanEnable"] boolValue];
        }
    
        if ([args.allKeys containsObject:@"type"]) {
            type = [args[@"type"] intValue];
        }
        
        if ([args.allKeys containsObject:@"takePhotoRotated"]) {
            takePhotoRotated = [args[@"takePhotoRotated"] boolValue];
        }
        
        if ([args.allKeys containsObject:@"iOSAutoStopScan"]) {
            autoStopScan = [args[@"iOSAutoStopScan"] boolValue];
        }
        
        if ([args.allKeys containsObject:@"iOSFullArea"]) {
            fullArea = [args[@"iOSFullArea"] boolValue];
        }
    }
    
    
    //初始化相机
    self.captureManager.delegate = self;
    
    self.captureManager.scanEnable = scanEnable;
    self.captureManager.takePhotoRotated = takePhotoRotated;
    self.captureManager.autoStopScan = autoStopScan;
    self.captureManager.type = type;
    self.captureManager.fullArea = fullArea;
    
    [self.captureManager congfigContentView:self];
}

///更新参数
- (void)updateParams:(NSDictionary *)args{
    
     if (args!=nil&&[args isKindOfClass:[NSDictionary class]]) {

        if ([args.allKeys containsObject:@"scanEnable"]) {
            BOOL scanEnable = [args[@"scanEnable"] boolValue];
            self.captureManager.scanEnable = scanEnable;
        }
        if ([args.allKeys containsObject:@"type"]) {
            NSInteger type = [args[@"type"] intValue];
            self.captureManager.type = type;
        }
        if ([args.allKeys containsObject:@"takePhotoRotated"]) {
            BOOL takePhotoRotated = [args[@"takePhotoRotated"] boolValue];
            self.captureManager.takePhotoRotated = takePhotoRotated;
        }
        if ([args.allKeys containsObject:@"ocrImgPath"]) {
            NSString* imgPath = [args valueForKey:@"ocrImgPath"];
            self.imgPath = imgPath;
        }
        if ([args.allKeys containsObject:@"ocrHeadPath"]) {
            NSString* headPath = [args valueForKey:@"ocrHeadPath"];
            self.headPath = headPath;
        }
    }
}

///重写变量获取方法
- (OcrPCaptureManager *)captureManager {
    if (!_captureManager) {
        _captureManager = [[OcrPCaptureManager alloc] init];
    }
    return _captureManager;
}

#pragma mark - CaptureDelegate
- (void)successWithInfo:(OcrPModel *)idInfo image:(UIImage *)image {
    NSLog(@"successWithInfo");
    
    if (self.successBlock) {
        self.successBlock([self getIdCardInfoDict:idInfo image:image]);
    }
    
    if (self.captureManager.autoStopScan==NO) {
        return;
    }
    self.successBlock = nil;
}

- (void)failureWithTitle:(NSString *)title message:(NSString *)message{
    if (self.failurelock) {
        self.failurelock(@"-1", [NSString stringWithFormat:@"%@，%@",title,message]);
    }
    
    if (self.captureManager.autoStopScan==NO) {
        return;
    }
    self.failurelock = nil;
}

- (NSDictionary*)getIdCardInfoDict:(OcrPModel*) idInfo image:(UIImage*)image{
    
    NSMutableDictionary* dic = [[NSMutableDictionary alloc]init];
    //没有出生日期birt
    [dic setValue:idInfo.name forKey:@"name"];
    [dic setValue:idInfo.gender forKey:@"sex"];
    [dic setValue:idInfo.nation forKey:@"folk"];
    [dic setValue:idInfo.address forKey:@"addr"];
    [dic setValue:idInfo.num forKey:@"num"];
    [dic setValue:idInfo.issue forKey:@"issue"];
    [dic setValue:idInfo.valid forKey:@"valid"];
    //保存图片
    NSString* path = self.imgPath;
    if([NSString isBlankString:path]){
        NSArray *arr = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);;
        NSString *documentPath = [arr lastObject];
        path = [documentPath stringByAppendingPathComponent:@"scanImgPath.jpg"];
    }
    
    NSString *timeString = [NSString stringWithFormat:@"%0.f", [NSDate.date timeIntervalSince1970]];
    path = [path stringByReplacingOccurrencesOfString:path.lastPathComponent withString:[NSString stringWithFormat:@"%@%@",timeString,path.lastPathComponent]];
    
    /// 写入覆盖失败，待优化
    
    //图片质量0-1
    BOOL writed = [UIImageJPEGRepresentation(image, 1) writeToFile:path atomically:YES];
    if (writed) {
        NSLog(@"图片写入成功");
    } else {
        NSLog(@"图片写入失败");
    }
    //设置图片路径
    [dic setValue: path forKey:@"imgPath"];
    return dic;
}


@end
